<template>
	<view class="detail">
		<unicloud-db v-slot:default="{ data, loading, error, options }" ref="udb" @load="udbLoad" @error="udbError"
			:collection="tableList" :where="where" getone>
			<view v-if="error">{{ error.message }}</view>
			<view v-else-if="loading" class="article-loading">加载中...</view>
			<view v-else>
				<view class="container">
					<!-- {{data}} -->
					<view class="title">{{ data.title }}</view>
					<view class="userinfo">
						<view class="avatar">
							<u-avatar
								:src="data.user_id[0] ? data.user_id[0].avatar_file?data.user_id[0].avatar_file.url: '' : ''"
								size="65rpx"></u-avatar>
						</view>
						<view class="text">
							<view class="name">{{
                userName
              }}</view>
							<view class="small">
								<uni-dateformat format="yyyy年MM月dd日 hh:mm:ss" :date="data.publish_date">
								</uni-dateformat>
								{{ " · 发布于" }}
								{{ data.city }}
							</view>
						</view>
					</view>
					<view class="content">
						<u-parse :content="data.content" lazyLoad :tagStyle="riccStyle"></u-parse>
					</view>
				</view>
			</view>
		</unicloud-db>

		<view class="like" v-if="!udbLoading">
			<view class="btn" :class="{active: likeNot}" @click="lickBtn">
				<u-icon name="thumb-up" color="#fff" size="28"></u-icon>
				<text>{{ udbData.like_count ? udbData.like_count : "点赞" }}</text>
			</view>
			<view class="users">
				<!-- <u-avatar :urls="avatars" size="60rpx"></u-avatar> -->
				<u-avatar-group :urls="avatars" size="35" gap="0.4"></u-avatar-group>
			</view>
			<view class="text"><text class="num">{{ udbData.view_count || "0" }}</text>人看过</view>
		</view>

		<!-- 评论模块 -->
		<view class="comment" v-if="!udbLoading">
			<comment :receiveCommentObj="commentObj" ref="commentContent"></comment>
		</view>
		<!-- 评论输入框 -->
		<!-- <view class="comment-ipt"> -->
		<comment-frame v-if="!udbLoading" :commentObj="commentObjInput" @emitComment="handleComment"></comment-frame>
		<!-- </view> -->
	</view>
</template>

<script>
	import {
		selfIncreas
	} from '../../uniCloud-aliyun/cloudfunctions/articleOpera/index.obj';

	import {
		throttle,
		getUserInfo,
		isLogin
	} from "../../utils/common.js"

	import {
		store
	} from "@/uni_modules/uni-id-pages/common/store.js"

	const db = uniCloud.database();
	const userModule = db.collection("uni-id-users");
	const articleModule = db.collection("article");

	export default {
		onLoad(e) {
			this.article_id = e._id;
			// this.user_id = e.user_id
			this.where = `_id=='${e._id}'`;
			console.log('detail-onload', e);
			this.commentObj.article_id = e._id
			this.commentObj.user_id = e.user_id

			this.commentObjInput.article_id = e._id

			this.selfIncreaViewCount()
			this.getAvatars()
		},
		async onShow() {
			console.log('onshow--isLogin--store.hasLogin', store.hasLogin);
			// isLogin()
			// console.log('onshow--isLogin--isLogin()', isLogin());
			// 使用防抖函数
			this.throttleLike = throttle(4000, this.like)

			if (store.hasLogin) {
				this.likeSelect()
			}

		},
		data() {
			return {
				commentObj: {
					article_id: '',
					comment_type: 0,
					user_id: '',
				},
				commentObjInput: {
					article_id: '',
					comment_type: 0,
				},
				avatars: [],
				throttleLike: '',
				dataStore: store,
				likeNot: false,
				where: "",
				article_id: "",
				udbLoading: true,
				udbData: {},
				tableList: [
					articleModule.getTemp(),
					userModule.field("_id,username,nickname,avatar_file").getTemp(),
				],
				riccStyle: {
					p: "line-height:1.7em;font-size:16px;padding-bottom:10rpx",
					img: "margin:10rpx 0",
				},
			};
		},
		methods: {
			handleComment(data) {
				// console.log({
				// 	data
				// });
				this.$refs.commentContent.unshiftComment(data)
			},
			async getAvatars() {
				const articleT = db.collection('like').where(`article_id=='${this.article_id}'`).field('user_id')
					.getTemp()
				const userT = db.collection('uni-id-users').field('_id,avatar_file').getTemp()
				const res = await db.collection(articleT, userT).orderBy('publish_date desc').limit(6).get()
				console.log(res.result.data);
				this.avatars = res.result.data.map(item => {
					return item.user_id[0]?.avatar_file?.url
				})

			},

			async likeSelect() {
				const isLike = await this.isLike()
				// console.log({
				// 	isLike
				// });
				if (isLike) {
					this.likeNot = true
					console.log('onshow--isLike', isLike);
				}
			},
			lickBtn() {
				// console.log('lickBtn');
				// if (!store.hasLogin) return
				const noTime = this.throttleLike()
				noTime
					?
					uni.showToast({
						title: noTime,
						icon: 'none'
					}) :
					''
			},
			udbLoad(data, ended, pagination) {
				// `data` 当前查询结果 `ended` 是否有更多数据	 `pagination` 分页信息 HBuilderX 3.1.5+ 支持
				const udbDataRef = this.$refs.udb;

				// console.log('udbRef', udbDataRef, udbDataRef.loading, udbDataRef.dataList);
				this.udbData = data;
				// this.likeNot = 
				this.udbLoading = udbDataRef.loading;
				// 设置导航条标题
				uni.setNavigationBarTitle({
					title: data.title
				})
			},
			udbError(e) {
				// debugger
				console.log("udbError", e);
				uni.switchTab({
					url: "/pages/index/index",
				});
				setTimeout(() => {
					uni.showToast({
						title: "参数有误",
						icon: "error",
					});
				}, 1000);
			},
			async selfIncreaViewCount() {
				// console.log('selfIncreaViewCount');
				const result = await uniCloud.importObject('articleOpera', {
					customUI: true
				}).selfIncreas(this.article_id, 'view_count')
			},
			async like() {
				const isLike = await this.isLike()
				// 是否已经点过赞
				if (isLike) {
					// 已经点过赞
					this.likeNot = false
					this.udbData.like_count -= 1

					await db.collection("like").where(`article_id=="${this.article_id}" && user_id==$cloudEnv_uid`)
						.remove();
					await this.selfDecrementLikeCount()
					this.getAvatars()


				} else {
					// 未点赞
					this.likeNot = true
					this.udbData.like_count += 1

					await db.collection("like").add({
						article_id: this.article_id
					})
					await this.selfIncreaLikeCount()
					this.getAvatars()
				}
			},
			async selfDecrementLikeCount() {
				const result = await uniCloud.importObject('articleOpera', {
					customUI: true
				}).selfIncreas(this.article_id, 'like_count', -1)
			},
			async selfIncreaLikeCount() {
				const result = await uniCloud.importObject('articleOpera', {
					customUI: true
				}).selfIncreas(this.article_id, 'like_count')
			},
			async isLike() {
				let count = await db.collection("like")
					.where(`article_id=="${this.article_id}" && user_id==$cloudEnv_uid`).count()
				return count.result.total
			}

		},
		computed: {
			userName() {
				return getUserInfo.getUserName(this.udbData)
			},
			// commentObjCom() {
			// 	return delete this.commentObj.user_id
			// },
		},
		watch: {
			dataStore: {
				handler(newVal, oldVal) {
					this.likeSelect()
				},
				deep: true
			}
		},
	};
</script>

<style lang="scss" scoped>
	.article-loading {
		text-align: center;
	}

	.detail {
		background: #f8f8f8;
		min-height: calc(100vh - var(--window-top));

		.container {
			padding: 30rpx;
			background: #fff;

			.title {
				font-size: 46rpx;
				color: #333;
				line-height: 1.4em;
				font-weight: 600;
			}

			.userinfo {
				padding: 20rpx 0 50rpx;
				display: flex;
				align-items: center;

				.avatar {
					width: 60rpx;
					height: 60rpx;
					padding-right: 15rpx;

					image {
						width: 100%;
						height: 100%;
						border-radius: 50%;
					}
				}

				.text {
					font-size: 28rpx;
					color: #555;

					.small {
						font-size: 20rpx;
						color: #999;
					}
				}
			}

			.content {}
		}

		.like {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 80rpx 50rpx 50rpx;

			.btn {
				width: 260rpx;
				height: 120rpx;
				background: #e4e4e4;
				border-radius: 100rpx;
				color: #fff;
				display: flex;
				justify-content: center;
				align-items: center;
				flex-direction: column;
				font-size: 28rpx;

				.iconfont {
					font-size: 50rpx;
				}

				&.active {
					background: #0199fe;
				}
			}

			.text {
				font-size: 26rpx;
				color: #666;

				.num {
					color: #0199fe;
				}

				.spot {
					padding: 0 10rpx;
				}
			}

			.users {
				display: flex;
				justify-content: center;
				padding: 30rpx 0;

				image {
					width: 50rpx;
					height: 50rpx;
					border-radius: 50%;
					border: 3px solid #fff;
					margin-left: -20rpx;
				}
			}
		}
	}
</style>